import { _decorator, Component, Node, Vec3, random, randomRangeInt } from 'cc';
import { EnemyConfig } from './EnemyConfig';
import { GameManager } from './GameManager';
import { PlayerController } from './PlayerController';
import { RollBase } from './RollBase';
const { ccclass, property } = _decorator;

@ccclass('Enemy')
export class Enemy extends RollBase
{

    public Config: EnemyConfig

    private targetPos: Vec3 = new Vec3()
    private offsetPos: Vec3 = new Vec3()
    private isFlip: boolean = false

    start()
    {
        this.CurHP = this.Config.MaxHP
        this.MoveSpeed = this.Config.nMoveSpeed
        this.node.setPosition(this.Config.v2InitPos.x, this.Config.v2InitPos.y)
    }

    update(deltaTime: number)
    {
        if (GameManager.instance.IsGamePause > 0) {
            return
        }

        this.node.getPosition(this.CurPos)
        this.Config.Target.getPosition(this.targetPos)
        let player = this.Config.Target.getComponent(PlayerController)
        Vec3.subtract(this.offsetPos, this.targetPos, this.CurPos)
        if (this.offsetPos.lengthSqr() < 2500)
        {
            player.Hurt(1, this.node)
            return
        }
        Vec3.multiplyScalar(this.offsetPos, this.offsetPos.normalize(), this.MoveSpeed)
        Vec3.add(this.CurPos, this.CurPos, this.offsetPos)
        if (this.offsetPos.x > 0 && !this.isFlip)
        {
            this.node.setScale(new Vec3(-1, 1, 1))
            this.isFlip = true
        }
        this.node.setPosition(this.CurPos)
    }

    OnKill(source: Node)
    {
        if (source != null)
        {
            let r = randomRangeInt(0, 100)
            if (r <= 100) // 宝箱爆率
            {
                GameManager.instance.CreateChest(this.node.getPosition())
            }
            else if (r <= 100) // 经验掉率
            {
                GameManager.instance.CreateExp(this.node.getPosition())
            }
        }
        GameManager.instance.RemoveEnemy(this.Config.EID)
    }
}


